package com.fc.base.init;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.fc.base.annotation.autowired;
import com.fc.base.service.ICommonService;
import com.fc.service.ILoginInfoService;

public class ContextLoaderListener implements ServletContextListener {
	private String sourcePath = ContextLoaderListener.class.getClassLoader()
			.getResource("//").getPath();

	private Map<String, List<String[]>> map;

	public ContextLoaderListener() {
		if (System.getProperties().getProperty("os.name").toString()
				.toLowerCase().contains(InitContext.SYSTEM_WINDOWS)) {
			sourcePath = ContextLoaderListener.class.getClassLoader()
					.getResource("").getPath();
			"\\".equals(File.separator);
		} else if (System.getProperties().getProperty("os.name").toString()
				.toLowerCase().contains(InitContext.SYSTEM_LINUX)) {
			sourcePath = ContextLoaderListener.class.getClassLoader()
					.getResource("/").getPath();
		}
		map = new HashMap<String, List<String[]>>();
	}

	// 这个方法在Web应用服务做好接受请求的时候被调用。
	public void contextInitialized(ServletContextEvent event) {
		File classFolder = new File(sourcePath);
		bulidFile(classFolder);
		try {
			dualClassMap();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		// 遍历所有类
	}

	private void bulidFile(File file) {
		if (file.isDirectory()) {
			File[] classFolderChildren = file.listFiles();
			for (File fileTemp : classFolderChildren) {
				bulidFile(fileTemp);
			}
		} else {
			String fileName = file.getName();
			String filePath = file.getAbsolutePath();
			if (fileName.endsWith(InitContext.IOC_CLASS_ACTION)) {
				List<String[]> list = map.get(InitContext.IOC_MAP_KEY_ACTION);
				String[] classAry = new String[2];
				String qualifiedName = bulidQualifiedNameByPath(filePath);
				qualifiedName = qualifiedName.substring(0, qualifiedName
						.length() - 6);
				classAry[0] = fileName.substring(0, fileName.length() - 6);
				classAry[1] = qualifiedName;
				if (null == list) {
					list = new ArrayList<String[]>();
					list.add(classAry);
					map.put(InitContext.IOC_MAP_KEY_ACTION, list);
				} else {
					list.add(classAry);
					map.remove(InitContext.IOC_MAP_KEY_ACTION);
					map.put(InitContext.IOC_MAP_KEY_ACTION, list);
				}
			}
			if (fileName.endsWith(InitContext.IOC_CLASS_SERVICE)) {
				List<String[]> list = map.get(InitContext.IOC_MAP_KEY_SERVICE);
				String[] classAry = new String[2];
				String qualifiedName = bulidQualifiedNameByPath(filePath);
				qualifiedName = qualifiedName.substring(0, qualifiedName
						.length() - 6);
				classAry[0] = fileName.substring(0, fileName.length() - 6);
				classAry[1] = qualifiedName;
				if (null == list) {
					list = new ArrayList<String[]>();
					list.add(classAry);
					map.put(InitContext.IOC_MAP_KEY_SERVICE, list);
				} else {
					list.add(classAry);
					map.remove(InitContext.IOC_MAP_KEY_SERVICE);
					map.put(InitContext.IOC_MAP_KEY_SERVICE, list);
				}
			}
		}
	}

	private String bulidQualifiedNameByPath(String path) {
		String temp = path.substring(path.indexOf("\\WEB-INF\\classes\\") + 17);
		return temp;
	}

	private void dualClassMap() throws ClassNotFoundException {
		List<String[]> actionClassList = map
				.get(InitContext.IOC_MAP_KEY_ACTION);
		List<Map<String, Object>> iocList = new ArrayList<Map<String, Object>>();
		if (null != actionClassList)
			for (Iterator iterator = actionClassList.iterator(); iterator
					.hasNext();) {
				String[] classAry = (String[]) iterator.next();
				String qualifiedName = classAry[1];
				Class cls = Class
						.forName(qualifiedName.replaceAll("\\\\", "."));
				Field[] fields;
				fields = cls.getDeclaredFields();
				for (int i = 0; i < fields.length; i++) {
					Field field = fields[i];
					field.setAccessible(true);
					autowired ano = field.getAnnotation(autowired.class);
					String fieldName = field.getName();
					boolean anoValue = false;
					if (null != ano) {
						anoValue = ano.value();
						if (anoValue) {
							// 修改class文件注入service
							String serviceImplName = field.getType().getName()
									.toString().substring(1)
									+ InitContext.SERVICE_IMPLEMENT_SUFFIX;
							Map<String, Object> iocMap = new HashMap<String, Object>();
							ILoginInfoService service = (class.)Class.forName(serviceImplName).newInstance();
						}
					}
				}
			}
		List<String[]> serviceClassList = map
				.get(InitContext.IOC_MAP_KEY_SERVICE);
		if (null != serviceClassList)
			for (Iterator iterator = serviceClassList.iterator(); iterator
					.hasNext();) {
				String[] classAry = (String[]) iterator.next();
				System.out.println(classAry[0]);
			}
	}

	public void contextDestroyed(ServletContextEvent arg0) {
		System.out.println("destroy");
	}

}
